#!/bin/bash

set -euo pipefail

# Check if the the user has invoked the image with flags.
# eg. "{{ .BeatName }} -c {{ .BeatName }}.yml"
if [[ -z $1 ]] || [[ ${1:0:1} == '-' ]] ; then
  exec {{ .BeatName }} "$@"
else
  # They may be looking for a Beat subcommand, like "{{ .BeatName }} setup".
  subcommands=$({{ .BeatName }} help \
                  | awk 'BEGIN {RS=""; FS="\n"} /Available Commands:/' \
                  | awk '/^\s+/ {print $1}')

  # If we _did_ get a subcommand, pass it to {{ .BeatName }}.
  for subcommand in $subcommands; do
      if [[ $1 == $subcommand ]]; then
        exec {{ .BeatName }} "$@"
      fi
  done
fi

# If neither of those worked, then they have specified the binary they want, so
# just do exactly as they say.
exec "$@"
